package com.itheima.server.interceptor;

import com.itheima.domain.db.User;
import com.itheima.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 阿鹏
 * @date 2021/1/24 23:21
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        User user = userService.findUserByToken(token);
        if (user == null) {
            response.setStatus(401);
            return false;
        }

        // 把User绑定到当前线程上
        UserHolder.setUser(user);
        return true;
    }
}
